package com.budgetme.activities.fragments;

import java.util.ArrayList;

import com.budgetme.ui.fragments.DetailsFragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;


public class ItemFragmentAdapter<T extends DetailsFragment> extends FragmentStatePagerAdapter {
	private static final String TAG = ItemFragmentAdapter.class.getName();
	
	private final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
	
	private final Class<?> mClass;
	
	private final Context mContext;
	
	private Cursor mCursor;
	
    public ItemFragmentAdapter(Activity context, ViewPager pager, Class<?> clss) {
        super(context.getFragmentManager());
        mClass = clss;
        mContext = context;
    }
    
    public void addPage(int page, Bundle args) {
    	
    	ItemInfo info = new ItemInfo(page, args);
    	mItems.add(info);
    	notifyDataSetChanged();
    	
    }
    
    public void setCurrent(int id, ViewPager pager) {
        for (int i=0; i<mItems.size(); i++) {
            if (mItems.get(i).id == id) {
            	pager.setCurrentItem(i);
            }
        }
    }

	@Override
	public Fragment getItem(int position) {
		Log.d(TAG, "getItem(" + position + ")");
		
		return T.instantiate(mContext, mClass.getName(), mItems.get(position).args);
		
	}

	@Override
	public int getCount() {
		return mItems.size();
	}
	
    private static final class ItemInfo {
    	
        final int id;
        final Bundle args;

        ItemInfo(int id, Bundle args) {
            this.id = id;
            this.args = args;
        }
        
    }
    
    public void setItemPositions() {
    	
    	
    	int count = mCursor.getCount();
    	mCursor.moveToPosition(-1);
    	 
    	while (mCursor.moveToNext()) {
    		
    		int id = mCursor.getInt(mCursor.getColumnIndexOrThrow("_id"));
	    	int page = mCursor.getPosition();
	    	
    		Bundle args = new Bundle();
    		args.putInt(DetailsFragment.ARG_ID, id);
	    	
    		ItemInfo info = new ItemInfo(page, args);
        	mItems.add(info);
    		
    	}
    	 
    }
    
}